﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace GComp.Apps.EasyStock.DataModel.Common {
    public class QuoteQuery : YQLQuery {
        const string OneSymbolQuery = "select * from yahoo.finance.quotes where symbol = \"{0}\"";
        const string SymbolsQuery = "select * from yahoo.finance.quotes where symbol in ({0})";

        public QuoteQuery(string symbol) {
            _query = string.Format(OneSymbolQuery, symbol);
        }

        public QuoteQuery(IEnumerable<string> symbols) {
            StringBuilder sb = new StringBuilder();
            foreach (string sym in symbols) {
                if (sb.Length > 0)
                    sb.Append(", ");
                sb.Append('"').Append(sym).Append('"');
            }
            _query = string.Format(SymbolsQuery, sb.ToString());
        }

        public async Task<IEnumerable<StockQuote>> GetAnswerAsync() {
            XDocument doc = await GetXmlAnswerAsync();
            List<StockQuote> result = new List<StockQuote>();
            foreach (var quote in doc.Descendants("quote")) {
                result.Add(StockQuote.FromXml(quote));
            }
            return result;
        }

    }
}
